package com.nmdl.test2;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class MainActivity extends AppCompatActivity {


    private static final int REQUEST_PERMISSION_ACCESS_LOCATION = 1000;
    private static final int REQUEST_OPEN_BT_CODE = 1100;
    private BluetoothAdapter blueToothClient = BluetoothAdapter.getDefaultAdapter();
    private BluetoothReceiver bluetoothReceiver;
    private DevicesAdapter adapter;
    private String MAC = "54:6C:0E:35:78:18";
    //
    private TextView devices_title;
    private Button start_search_btn;
    private ProgressBar search_progress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        this.requestPermission();
        this.getBindDevice(null);
    }

    private void initView() {
        devices_title = findViewById(R.id.devices_title);
        start_search_btn = findViewById(R.id.start_search_btn);
        search_progress = findViewById(R.id.search_progress);
        RecyclerView devices_list = findViewById(R.id.devices_list);
        adapter = new DevicesAdapter(this, blueToothClient, new DevicesAdapter.ItemClickListener() {
            @Override
            public void itemClick(BluetoothDevice device) {
                DeviceActionFragment datePickerDialogFragment = DeviceActionFragment.newInstance(device, () -> {
                    BleHelper.connectDeviceService(blueToothClient, device, MainActivity.this);
//                    BleHelper.connectDevice(blueToothClient, device, MainActivity.this);//发送电脑成功
//                    BleHelper.connectDeviceAudio(blueToothClient, device, MainActivity.this);
                });
                FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
                datePickerDialogFragment.show(fragmentManager, "DeviceActionFragment");
            }

            @Override
            public void bondClick(BluetoothDevice device) {
                if (blueToothClient.isDiscovering()) blueToothClient.cancelDiscovery();
                BleHelper.bond(device);
            }

            @Override
            public void connectClick(BluetoothDevice device) {
                if (blueToothClient.isDiscovering()) blueToothClient.cancelDiscovery();
                BleHelper.connectDevice(blueToothClient, device, MainActivity.this);
            }
        });
        devices_list.setAdapter(adapter);
        devices_list.setLayoutManager(new LinearLayoutManager(this));
    }

    public void initListener() {
        if (bluetoothReceiver != null) return;
        //注册广播
        bluetoothReceiver = new BluetoothReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        intentFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(bluetoothReceiver, intentFilter);
    }

    private boolean openBluetooth(BluetoothAdapter blueToothClient) {
        if (blueToothClient != null && !blueToothClient.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, REQUEST_OPEN_BT_CODE);
            return false;
        }
        return true;
    }

    public void search(View view) {
        Boolean opened = this.openBluetooth(blueToothClient);
        if (!opened) return;
        start_search_btn.setEnabled(false);
        search_progress.setVisibility(View.VISIBLE);
        this.initListener();
        devices_title.setText("发现的设备");
        if (blueToothClient.isDiscovering()) blueToothClient.cancelDiscovery();
        blueToothClient.startDiscovery();
        Log.e(getPackageName(), "开始搜索");
    }

    /**
     * 获取已绑定和已连接设备 todo 需要将绑定的设备显示到单独的RecyclerView上，防止已绑定的设备在扫描列表里面找不到。。。
     */
    public void getBindDevice(View view) {
        Boolean opened = this.openBluetooth(blueToothClient);
        if (!opened) return;
        List<BluetoothDevice> bondDevices = new ArrayList<>();//已经连接的设备
        Set<BluetoothDevice> bondedDevices = blueToothClient.getBondedDevices();
        bondDevices.addAll(bondedDevices);
    }

    /**
     * 主动连接
     *
     * @param view
     */
    public void connectGatt(View view) {
        String macAddress = "EC:8C:9A:53:4C:BD";
//        String macAddress = "60:F4:3A:E0:1A:C5";//耳机
        BluetoothDevice bluetoothDevice = blueToothClient.getRemoteDevice(macAddress);
        BleHelper.bond(bluetoothDevice);
        BleHelper.connectDevice(blueToothClient, bluetoothDevice, this);

    }

    public void toTestActivity(View view) {
        startActivity(new Intent(this, TestActivity.class));
    }

    public void toTestActivity(BluetoothDevice device) {
        Intent intent = new Intent(this, TestActivity.class);
        intent.putExtra("device", device);
        startActivity(intent);
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkAccessFinePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            if (checkAccessFinePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSION_ACCESS_LOCATION);
                Log.e(getPackageName(), "没有权限，请求权限");
                return;
            }
            Log.e(getPackageName(), "已有定位权限");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.e(getPackageName(), "开启权限permission granted!");
                } else {
                    Log.e(getPackageName(), "没有定位权限，请先开启!");
                    Toast.makeText(this, "权限没有开启！", Toast.LENGTH_SHORT).show();
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_OPEN_BT_CODE) {
            Boolean success = resultCode == RESULT_OK;
            showToast(success ? "打开蓝牙成功！" : "打开蓝牙失败！");
            if (success) search(null);
            if (success) getBindDevice(null);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bluetoothReceiver != null) {
            unregisterReceiver(bluetoothReceiver);
            bluetoothReceiver = null;
        }
    }

    class BluetoothReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("=============???BluetoothReceiver???=============" + intent.getAction());
            if (intent.getAction().equals(BluetoothDevice.ACTION_FOUND)) {
                System.out.println("BluetoothReceiver=============ACTION_FOUND");
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                adapter.updateDevice(device);
                if (device.getAddress().equals(MAC)) {
                    showToast("扫描到目标设备");
                    toTestActivity(device);
                }
            } else if (intent.getAction().equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
                System.out.println("BluetoothReceiver=============ACTION_BOND_STATE_CHANGED");
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                adapter.updateDevice(device);
                getBindDevice(null);
                switch (device.getBondState()) {
                    case BluetoothDevice.BOND_NONE:
                        Log.e(getPackageName(), "取消配对");
                        break;
                    case BluetoothDevice.BOND_BONDING:
                        Log.e(getPackageName(), "配对中");
                        break;
                    case BluetoothDevice.BOND_BONDED:
                        Log.e(getPackageName(), "配对成功");
                        break;
                }
            } else if (intent.getAction().equals(BluetoothDevice.ACTION_PAIRING_REQUEST)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (!device.getAddress().equals("54:6C:0E:35:78:18")) return;
                String pin = "123456";
                System.out.println("BluetoothReceiver=============ACTION_PAIRING_REQUEST");
                //1.确认配对
                ClsUtils.setPairingConfirmation(device.getClass(), device, true);
                //2.终止有序广播
                Log.i("order...", "isOrderedBroadcast:" + isOrderedBroadcast() + ",isInitialStickyBroadcast:" + isInitialStickyBroadcast());
                abortBroadcast();//如果没有将广播终止，则会出现一个一闪而过的配对框。
                //3.调用setPin方法进行配对...
                boolean ret = ClsUtils.setPin(device.getClass(), device, pin);
            } else if (intent.getAction().equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                start_search_btn.setEnabled(true);
                search_progress.setVisibility(View.GONE);
            } else if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                //没有进入这里？？？？都不会监听到蓝牙开关状态
                int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                switch (blueState) {
                    case BluetoothAdapter.STATE_TURNING_ON:
                        break;
                    case BluetoothAdapter.STATE_ON://打开成功
                        showToast("打开蓝牙成功===！");
                        search(null);
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        break;
                    case BluetoothAdapter.STATE_OFF://关闭成功
                        showToast("关闭蓝牙成功===！");
                        break;
                }
            } else if (intent.getAction().equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
                showToast("连接成功！");
            }
        }
    }
}